package com.atguigu.gmall.common.config.minio.service.impl;

import com.atguigu.gmall.common.config.minio.MinioProperties;
import com.atguigu.gmall.common.config.minio.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;


public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws Exception {
        // 文件名唯一
        String filename = UUID.randomUUID().toString().replace("-","") + "_" + file.getOriginalFilename();
        InputStream fis = file.getInputStream();

        // 创建MinioClient
        MinioClient client = new MinioClient(minioProperties.getEndpoint(), minioProperties.getAccessKey(), minioProperties.getSecretKey());

        boolean mall = client.bucketExists(minioProperties.getBucketName());
        if (!mall){
            client.makeBucket(minioProperties.getBucketName());
        }

        PutObjectOptions options = new PutObjectOptions(file.getSize(), -1L);

        // 上传文件
        client.putObject(minioProperties.getBucketName(),filename,fis,options);

        // 拿到文件的访问路径
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + filename;

        return url;
    }
}
